#ifndef __M_FMT_H__
#define __M_FMT_H__

#include "level.hpp"
#include "message.hpp"
#include <memory>
#include <vector>
#include <sstream>
#include <cassert>

namespace log
{
    // 实现各个消息子项类
    // 1. 抽象出一个共有基类，便于不同子类放在一个容器里遍历
    // 2. 各个子类对不同类型的消息进行不同的处理
    class FormatItem
    {
    public:
        using ptr = std::shared_ptr<FormatItem>;
        virtual void format(std::ostream &out, LogMsg &msg) = 0;
    };

    class MsgFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, LogMsg &msg) override
        {
            out << msg._payload;
        }
    };
    class LevelFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, LogMsg &msg) override
        {
            out << Level::toString(msg._level);
        }
    };
    class LoggerFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, LogMsg &msg) override
        {
            out << msg._logger;
        }
    };
    class ThreadFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, LogMsg &msg) override
        {
            out << msg._tid;
        }
    };
    class TimeFormatItem : public FormatItem
    {
    public:
        TimeFormatItem(const std::string &fmt = "%H%M%S") : _time_fmt(fmt) {}
        void format(std::ostream &out, LogMsg &msg) override
        {
            struct tm t;
            localtime_r(&msg._time, &t); // 将时间挫的内容转换成格式并保存在t中
            char tmp[32] = {0};
            strftime(tmp, sizeof(tmp) - 1, _time_fmt.c_str(), &t); // 按_time_fmt格式将t中的时间转换到tmp里
            out << tmp;
        }

    private:
        std::string _time_fmt; // 时间格式
    };
    class FileFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, LogMsg &msg) override
        {
            out << msg._file;
        }
    };
    class LineFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, LogMsg &msg) override
        {
            out << msg._line;
        }
    };
    class TabFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, LogMsg &msg) override
        {
            out << "\t";
        }
    };
    class NLineFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, LogMsg &msg) override
        {
            out << "\n";
        }
    };
    class OtherFormatItem : public FormatItem
    {
    public:
        OtherFormatItem(const std::string &str) : _str(str) {}
        void format(std::ostream &out, LogMsg &msg) override
        {
            out << _str;
        }

    private:
        std::string _str;
    };

    class Formatter
    {
    public:
        using ptr = std::shared_ptr<Formatter>;
        /*
            %d ⽇期
            %T 缩进
            %t 线程id
            %p ⽇志级别
            %c ⽇志器名称
            %f ⽂件名
            %l ⾏号
            %m ⽇志消息
            %n 换⾏
        */
    public:
        Formatter(const std::string &pattern = "[%d{%H:%M:%S}][%t][%p][%c][%f:%l]%T%m%n")
            : _pattern(pattern)
        {
            assert(parsePattern());
        }
        // 对LogMsg的消息格式化
        std::string format(LogMsg &msg)
        {
            std::stringstream ss;
            for (auto &it : _items)
            {
                it->format(ss, msg);
            }
            return ss.str();
        }

    private:
        // 对格式化规则字符串进行解析
        bool parsePattern()
        {
            //  默认格式 "%d{%H:%M:%S}%T%t%T[%p]%T[%c]%T%f:%l%T%m%n"
            std::vector<std::pair<std::string, std::string>> fmt_order;
            size_t pos = 0;
            std::string key, val;
            while (pos < _pattern.size())
            {
                // 1.判断 %
                if (_pattern[pos] != '%')
                {
                    val.push_back(_pattern[pos++]);
                    continue;
                }
                // 处理 %%
                if (pos + 1 < _pattern.size() && _pattern[pos + 1] == '%')
                {
                    val.push_back('%');
                    pos += 2;
                    continue;
                }
                // 这里表示处理格式化字符串
                if (val.empty() == false)
                {
                    fmt_order.push_back(std::make_pair("", val));
                    val.clear();
                }
                // pos指向%位置
                pos += 1;
                if (pos == _pattern.size())
                {
                    std::cout << "%之后，没有对应的格式化字符！\n";
                    return false;
                }
                key = _pattern[pos];
                pos += 1; // 指向格式化后一个的位置
                if (pos < _pattern.size() && _pattern[pos] == '{')
                {
                    pos += 1; // 指向 { 之后，子规则的起始位置
                    while (pos < _pattern.size() && _pattern[pos] != '}')
                    {
                        val.push_back(_pattern[pos++]);
                    }
                    // 到末尾，还没碰到}代表格式错误
                    if (pos == _pattern.size())
                    {
                        std::cout << "子规则{}匹配错误！\n";
                        return false;
                    }
                    pos += 1; // 此时pos指向 }
                }
                fmt_order.push_back(std::make_pair(key, val));
                key.clear();
                val.clear();
            }
            // 2.  创造子项数组成员
            for (auto &it : fmt_order)
            {
                _items.push_back(createItems(it.first, it.second));
            }
            return true;
        }
        FormatItem::ptr createItems(const std::string &c, const std::string &val)
        {
            if (c == "d")
                return std::make_shared<TimeFormatItem>(val);
            if (c == "T")
                return std::make_shared<TabFormatItem>();
            if (c == "t")
                return std::make_shared<ThreadFormatItem>();
            if (c == "p")
                return std::make_shared<LevelFormatItem>();
            if (c == "c")
                return std::make_shared<LoggerFormatItem>();
            if (c == "f")
                return std::make_shared<FileFormatItem>();
            if (c == "l")
                return std::make_shared<LineFormatItem>();
            if (c == "m")
                return std::make_shared<MsgFormatItem>();
            if (c == "n")
                return std::make_shared<NLineFormatItem>();
            if (c == "")
                return std::make_shared<OtherFormatItem>(val);
            std::cout << "没有对应的格式化字符：%" << c << std::endl;
            abort();
            return FormatItem::ptr();
        }
    private:
        std::string _pattern;
        std::vector<FormatItem::ptr> _items;
    };
}

#endif